package com.leantech.android.browser.ui.favorites

import android.content.Context
import android.os.Bundle
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import androidx.viewpager2.widget.ViewPager2
import com.google.android.material.tabs.TabLayoutMediator
import com.leantech.android.browser.R
import com.leantech.android.browser.databinding.ActivityFavoritesBinding
import com.leantech.android.browser.ui.BaseActivity
import com.leantech.android.browser.ui.favorites.vm.BrowserHistoryViewModel
import com.leantech.android.browser.ui.favorites.vm.FavoritesViewModel
import com.leantech.android.browser.utils.onThrottleClick
import com.leantech.android.browser.views.SkinTabLayout
import com.qmuiteam.qmui.kotlin.skin
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.flow.firstOrNull
import kotlinx.coroutines.launch
import org.koin.androidx.viewmodel.ext.android.viewModel
import org.koin.core.component.KoinComponent
import splitties.activities.start

class FavoritesActivity : BaseActivity(), KoinComponent {
    companion object {
        private const val ExtraSelectedPosition = "selectedPosition"

        fun start(context: Context, position: Int = 0) {
            context.start<FavoritesActivity> {
                putExtra(ExtraSelectedPosition, position)
            }
        }

    }

    private lateinit var binding: ActivityFavoritesBinding
    private lateinit var pagerAdapter: FavoritesPagerAdapter
    private val favoritesViewModel by viewModel<FavoritesViewModel>()
    private val browserHistoryViewModel by viewModel<BrowserHistoryViewModel>()


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        binding = ActivityFavoritesBinding.inflate(layoutInflater)
        setContentView(binding.root)

        initView()
        collectFlow()
    }

    private fun initView() {

        binding.btnBack.onThrottleClick {
            finish()
        }

        binding.btnSetting.onThrottleClick {
            when (binding.tabLayout.selectedTabPosition) {
                0 -> favoritesViewModel.toggleFavoriteEditMode()
                1 -> browserHistoryViewModel.toggleHistoryEditMode()
            }
        }

        pagerAdapter = FavoritesPagerAdapter(this)
        binding.viewPager.adapter = pagerAdapter
        binding.viewPager.offscreenPageLimit = 1
        binding.viewPager.currentItem = intent.getIntExtra(ExtraSelectedPosition, 0)
        binding.viewPager.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
            override fun onPageSelected(position: Int) {
                lifecycleScope.launch {
                    if (position == 0) {
                        val favoriteCount = favoritesViewModel.favoritesCountFlow.firstOrNull() ?: 0
                        binding.btnSetting.isEnabled = favoriteCount > 0
                    } else if (position == 1) {
                        val historyCount =
                            browserHistoryViewModel.historyCountFlow.firstOrNull() ?: 0
                        binding.btnSetting.isEnabled = historyCount > 0
                    }
                }
            }
        })

        TabLayoutMediator(binding.tabLayout, binding.viewPager) { tab, position ->
            when (position) {
                0 -> {
                    tab.setText(R.string.tab_favorites)
                }

                1 -> {
                    tab.setText(R.string.tab_history)
                }
            }
        }.attach()

        binding.tabLayout.skin {
            custom(SkinTabLayout.KeyTabBackground, R.attr.app_skin_favorites_tab_background)
        }

    }

    private fun collectFlow() {
        lifecycleScope.launch {
            repeatOnLifecycle(Lifecycle.State.STARTED) {
                launch {
                    favoritesViewModel.favoritesCountFlow.collectLatest {
                        if (binding.viewPager.currentItem == 0) {
                            binding.btnSetting.isEnabled = it > 0
                        }
                    }
                }

                launch {
                    browserHistoryViewModel.historyCountFlow.collectLatest {
                        if (binding.viewPager.currentItem == 1) {
                            binding.btnSetting.isEnabled = it > 0
                        }
                    }
                }

            }
        }
    }
}